#include <ctime>
#include "CGame.h"
#include "CEngineState.h"
#include "CDXRenderWin32.h"
using namespace std;



CGame::CGame(void)
{
	
}


CGame::~CGame(void)
{
	
}

CGame* CGame::GetInstance(void)
{
	static CGame instance;
	return &instance;
}

void CGame::Initialize(HWND hWnd, HINSTANCE hInstance, int nScreenWidth, int nScreenHeight, bool bIsWindowed)
{
	//Initialize Renderer
	m_DX = CDXRenderWin32::GetInstance();
	m_DX->Init(hWnd, nScreenWidth, nScreenHeight,false);

	srand(unsigned int(time(0)));
	m_hGameWindow = hWnd;
	m_nScreenHeight = nScreenHeight;
	m_nScreenWidth = nScreenWidth;
	ChangeState(new CEngineState());
	
}

void CGame::Shutdown(void)
{
	//	Shutdown in the OPPOSITE order you initialized in.
	m_DX->Shutdown();
}

bool CGame::Main(void)
{

	// Calculate the elapsed time
	DWORD dwCurrentTime = GetTickCount();

	// Calculate the difference between the current and the previous time
	// Use m_fElapsedTime to pass into update.
	m_fElapsedTime = (float)(dwCurrentTime - m_dwPreviousTime)/1000.0f;

	m_dwPreviousTime = dwCurrentTime;

	//Input
	if (m_vStates.size())
		if(!m_vStates[m_vStates.size()-1]->Input())
			return false;
	

	//Update
	if (m_vStates.size())
		m_vStates[m_vStates.size()-1]->Update(m_fElapsedTime);

	//Render
	m_DX->Clear(D3DCOLOR_XRGB(0, 0, 0));

	for (unsigned i = 0; i < m_vStates.size(); ++i)
	{
		m_vStates[i]->Render();
	}

	return true;
}

void CGame::ChangeState(IGameState* pNewState)
{
	for(int i = (int)m_vStates.size()-1; i >= 0; i-- )
	{
		if (m_vStates[i] && !m_vStates.empty())
		{
			m_vStates[i]->Exit();
			delete m_vStates[i];
			m_vStates.pop_back();
		}

	}
	AddState(pNewState);
}

void CGame::AddState(IGameState *pNewState)
{
	m_vStates.push_back(pNewState);

	if (m_vStates[m_vStates.size()-1])
		m_vStates[m_vStates.size()-1]->Enter();
}

void CGame::PreviousState()
{
	if(1 == m_vStates.size())
		return;

	m_vStates[m_vStates.size()-1]->Exit();
	delete m_vStates[m_vStates.size()-1];
	m_vStates.pop_back();
}
